<template>
  <div class="fixed-container">
    <div class="fixed-content">
      <div class="panel-container">
        <div class="panel-content">
          <div class="panel-line">
            <el-radio-group
              v-model="tabActive"
              style="margin-right: 30px"
              size="mini"
              @change="handleChange"
            >
              <el-radio-button
                v-for="item in tabList"
                :key="item.id"
                :label="item.id"
                >{{ item.label }}</el-radio-button
              >
            </el-radio-group>
            <el-date-picker
              size="mini"
              v-model="dateRange"
              @change="handleRangeChange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
            <slot name="end"></slot>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { formatDate, getDay } from '@/utils/index'
export default {
  name: 'PanelTab',
  data() {
    return {
      tabActive: -1,
      tabList: [
        { id: 0, label: '今天' },
        { id: 1, label: '昨天' },
        { id: 2, label: '最近7天' },
        { id: 3, label: '最近30天' }
      ],
      dateRange: '',
      time: ''
    }
  },
  mounted() {
    this.init()
  },
  destroyed() {},
  methods: {
    init() {
      this.tabActive = 0
      this.handleChange(0)
    },
    handleChange(value) {
      const today = new Date()
      if (value === 0) {
        this.time = {
          start: today,
          end: today
        }
      } else if (value === 1) {
        this.time = {
          start: getDay(-1),
          end: getDay(-1)
        }
      } else if (value === 2) {
        this.time = {
          start: getDay(-6),
          end: today
        }
      } else if (value === 3) {
        this.time = {
          start: getDay(-29),
          end: today
        }
      }
      this.dateRange = [this.time.start, this.time.end]
      this.timeChange()
    },
    handleRangeChange(value) {
      if (!value) {
        this.tabActive = 0
        this.handleChange(0)
        return
      }
      this.time = {
        start: value[0],
        end: value[1]
      }
      this.tabActive = -1
      this.timeChange()
    },
    timeChange() {
      this.$emit('change', {
        start_time: this.formatDate(this.time.start),
        end_time: this.formatDate(this.time.end)
      })
    },
    formatDate(date) {
      return formatDate(date, 'Y-M-D')
    }
  }
}
</script>

<style scoped lang="scss">
.fixed-container {
  position: fixed;
  right: 0;
  top: 84px;
  width: calc(100% - 140px);
  padding: 10px;
  padding-bottom: 0;
  z-index: 10;
  background: #f0f1f4;
}
.panel-container {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  margin: 0;
}
</style>
